﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace YGame.Base.Message
{
	/// <summary>
	/// 客户端的消息分发处理
	/// 我们的消息直接指明类名
	/// </summary>
	public class ClientMsgDispatcher
	{
		Dictionary<string, IMessageHandler> _container;

		public ClientMsgDispatcher()
		{
			_container = new Dictionary<string, IMessageHandler>();
		}

		public void Init(IGameServerProvider pGameServerProvider)
		{
			pGameServerProvider.ReceiveMessage += pGameServerProvider_ReceiveMessage;
		}

		void pGameServerProvider_ReceiveMessage(object sender, ReceiveMessageArgs e)
		{
			IMessageHandler messageHandler;
			if (_container.TryGetValue(e.Message.MessageID, out messageHandler))
			{
				messageHandler.OnReceive(e.Message);
			}
		}

		public void AddListener(Type listenerType)
		{
			string typeName = listenerType.FullName;

			// 检查类型是否为消息处理器
			if (listenerType.GetInterface(typeof(IMessageHandler).FullName) == null)
			{
				throw new ApplicationException("加载消息处理器不是基础接口类型:IMessageHandler");
			}

			IMessageHandler messageHandler = Activator.CreateInstance(listenerType) as IMessageHandler;

			// 先检查是否已经加载过
			if (_container.ContainsKey(typeName))
			{
				throw new ApplicationException("重复加载消息处理器:" + typeName);
			}

			_container.Add(typeName, messageHandler);
			Trace.Write(string.Format("加载消息处理器: {0} \r\n", typeName));

		}

	}
}
